/**
 * 公共插件
 * Created by junr on 2017/6/14.
 */
import webUploader from 'webuploader'
import config from '~src/config.js';
import Viewer from '~plugins/lib/js/viewer.min.js'
export default {
    //获取数组里的索引
    getArrIndex: function (arr,item) {
        if(!this.length || !item) return -1
        var i = 0,
            len = arr.length
        for(;i<len;i++){
            if(arr[i] == item) return i
        }
        return -1
    },
    removeLocal :function(key){
        window.localStorage.removeItem(key)
    },
    setLocal:function(key,value){
        window.localStorage[key]=JSON.stringify(value)
    },
    getLocal:function(key){
        return JSON.parse(window.localStorage[key] || '{}')
    },
    getCurrMenu:function (url) {
        var parentMenu = $_fn.getLocal('parentMenu')
       // return parentMenu.children.find(li => li.path === url)
       return parentMenu.children.find(li => url.indexOf(li.path)>=0)
    },
    layer:function(){
        this.index++
        var html='<div class="layui-layer layui-layer-loading layer-anim" id="layui-layer"><div class="layui-layer-content layui-layer-loading2"></div></div>'
        function show() {
            $("#layui-layer").length == 0 && $('body').append(html)
        }
        function hide() {
            $('.layui-layer').remove()
        }
        return {
            show:show,
            hide:hide
        }
    },
    //过滤小数点
    fdot:function (value,_this) {
        var inputVal
        // var _value = parseFloat(_this.value).toFixed(2)
        inputVal =  value.replace(/[^\d.]/g, '').replace(/^\./g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^\d+(\.\d{3})/g, '')
        if (value.substr(0, 1) === '0' && value.substr(1, 1) !== '.') {
            inputVal = '0'
        }
        _this.value = inputVal
    },
    newLineBySign: function(value){
        value = $.trim(value)
        var result=''
        if(value.indexOf('\n')>0) {
            result=value.replace(/(\n)/g,'$1\n')
            result=result.replace(/(\n)/g,'')
        }
        return result
    },
    applyShow: function (params,obj){
        for(var item in obj){
            obj[item] = false
        }
        obj[params] = true
    },
    //字符串转对象
    _paramValues: function (str) {
        var param = {}
        if (!this.isNull(str)) {
            var list = str.split(',')
            for (var i = 0; i < list.length; i++) {
                var val = list[i]
                var values = val.split(':')
                if (values.length == 2) {
                    param[values[0]] = values[1]
                }
            }
        }
        return param
    },
    /** 验证是否是空 true 空 false 不是空 */
    isNull: function (text) {
        if (text == null || text == undefined || $.trim(text).length <= 0) {
            text = text + ''
            if (isNaN(text)) {
                return true
            } else {
                if ($.trim(text).length <= 0) {
                    return true
                }
            }
        }
        return false
    },
    focus: function (self){
        var pubList =  $('.public-bgListNav .public-List')
        console.log(pubList.length)
        pubList.removeClass('publicListHover').eq(self).addClass('publicListHover')
    },
    getAdminId: function(){
        var storages = localStorage.getItem('userHelp');
        if(storages) return JSON.parse(storages).admin.id
    },
    tabClick: function(event){
        var _tr = $(event.target).parents('tr')
        if(_tr.hasClass('table-focus')){
            _tr.removeClass('table-focus')
            // _tr.find('input').removeAttr('checked')
            _tr.find('input').prop('checked', '')
        }
        else{
            _tr.addClass('table-focus')
            _tr.find('input').prop('checked',true)
        }
    },
    //全选
    ch_id_all: function(e,name){
        var _checked = $(':checkbox[name=' + name + ']')
        if($(e.target).prop('checked')){
            $('.dataList table tbody tr').addClass('table-focus')
            _checked.each(function(){
                if(!$(this).attr('disabled')) {
                    $(this).prop('checked', true)
                }
            })
        }else{
            $('.dataList table tbody tr').removeClass('table-focus')
            _checked.each(function(){
                // $(this).removeAttr('checked')
                if(!$(this).attr('disabled')){
                   $(this).prop('checked','')
                }
            })
        }
    },
    //获取选中项
    _fromCheckValue :function (name, split, filter) {
        var ids = ''
        if (this.isNull(split)) {
            split = ','
        }
        $(':checkbox[name=' + name + ']').each(function () {
            if ($(this).is(':checked')) {
                if(filter){
                    if($(this).attr('oper-data')==filter){
                        if (ids == '') {
                        ids += $(this).val()
                        } else {
                            ids += split + $(this).val()
                        }
                    }

                }
                else{
                    if (ids == '') {
                        ids += $(this).val()
                    } else {
                        ids += split + $(this).val()
                    }
                }
                
                console.log('ng-click',$(this),$(this).attr('oper-data'))
            }
        })
        return ids
    },
    getRouteId: function(){
        var storages = localStorage.getItem('userHelp')
        if(storages) return JSON.parse(storages).admin.roleid
    },
    //自动监控
    clickBind :function () {
        //统计字数
        this.showTextLength()
        //文本框只能输入数字
        this.isNum()
    },
    isEmptyObject: function( obj ) {
        for ( var name in obj ) {
            return false;
        }
        return true;
    },
    /***
     * 统计字数
     * @memberOf {TypeName}
     * @return {TypeName}
     */
    showTextLength: function () {
        //console.log('showTextLength')
        var _this = this
        $('[data-tag=textLength]').each(function () {
            var maxLength = $(this).attr('maxlength')
            if (isNaN(maxLength)) {
                return
            }
            var showTag = $(this).attr('showTag')
            if (_this.isNull(showTag)) {
                return
            }
            var value = $(this).val()
            //console.log('value='+value)
            if (!_this.isNull(value)) {
                $('#' + showTag).html(maxLength - value.length)
            }
            var lengthText = function (_this) {
                var val = $(_this).val()
                var length = maxLength - val.length
                $('#' + showTag).html(length)
            }
            $(this).keypress(function () {
                lengthText(this)
            })
            $(this).keydown(function () {
                lengthText(this)
            })
            $(this).keyup(function () {
                lengthText(this)
            })
        })
    },
    /**
    * 图片多图上传
    * @param callback
    */

    ueditorImg : function (callback) {
        var upload = $('[data-tag="ueloadImg"]')
        if (upload.length <= 0) {
            console.log('上传控件不存在')
            return
        }
        this.ueditorEdiet(upload, callback)
    },
    //
    //加载编辑器
    ueditorEdiet:function(upload, callback) {
        upload.each(function () {
            /** 加载JS结束 **/
            var _btn = $(this)
            var name = _btn.attr('name')
            var html = '<script id="' + name + '" type="text/plain" style="width:10pxheight:10px"></script>'
            _btn.append(html)
            var _editor = window.UE.getEditor(name)
            _editor.ready(function () {
                //设置编辑器不可用
                //_editor.setDisabled()  这个地方要注意 一定要屏蔽
                //隐藏编辑器，因为不会用到这个编辑器实例，所以要隐藏
                _editor.hide()
                //侦听图片上传
                _editor.addListener('beforeinsertimage', function (t, arg) {
                    var html = []
                    for (var a in arg) {
                        html.push(arg[a].src)
                    }
                    if (callback != null && callback != undefined) {
                        callback(html,_btn)//返回地址集合
                        console.log($('#gallery'+_btn.attr('data-key')).length>0)
                    }
                })
    
            })
            //弹出图片上传的对话框
            $(this).on('click', function () {
                if(_editor){
                    var myImage = _editor.getDialog('insertimage')
                    myImage.open()
                }
            })
        })
    },
    // //加载编辑器
    // ueditorEdiet:function(upload, callback) {
    //     upload.each(function () {
    //         /** 加载JS结束 **/
    //         var _btn = $(this)
    //         var name = _btn.attr('name')
    //         var html = '<script id="' + name + '" type="text/plain" style="width:10pxheight:10px"></script>'
    //         _btn.append(html)
    //         var _editor = window.UE.getEditor(name)
    //         _editor.ready(function () {
    //             //设置编辑器不可用
    //             //_editor.setDisabled()  这个地方要注意 一定要屏蔽
    //             //隐藏编辑器，因为不会用到这个编辑器实例，所以要隐藏
    //             _editor.hide()
    //             //侦听图片上传
    //             _editor.addListener('beforeinsertimage', function (t, arg) {
    //                 var html = []
    //                 for (var a in arg) {
    //                     html.push(arg[a].src)
    //                 }
    //                 if (callback != null && callback != undefined) {
    //                     callback(html,_btn)//返回地址集合
    //                     console.log($('#gallery'+_btn.attr('data-key')).length>0)
    //                 }
    //             })
    //
    //         })
    //         //弹出图片上传的对话框
    //         $(this).on('click', function () {
    //             if(_editor){
    //                 var myImage = _editor.getDialog('insertimage')
    //                 myImage.open()
    //             }
    //         })
    //     })
    // },
    scrollShow:function(ele){
        var winBox = $('.winBox')[0]
        var winBox1 = $('.winBox1')[0]
        var headerBox = $('.'+ ele +' .headerBox')[0]
        var centerBox = $('.'+ ele +' .centerBox')[0]
        var footerBox = $('.'+ ele +' .footerBox')[0]
        var resultPadd = $('.resultPadd')[0]



        if(footerBox)
        {
            if((winBox1.offsetTop - winBox1.offsetHeight/2 ) <=50)
            {
                centerBox.style.height = winBox.clientHeight - headerBox.clientHeight - footerBox.clientHeight - 100 + 'px'
            }
        }
        else
        {
            if(Math.floor(winBox1.offsetTop - (winBox1.offsetHeight+559)/2 ) <=50)
            {
                var aa = winBox.clientHeight - headerBox.clientHeight - 100
                $('.'+ ele +' .centerBox').css('max-height',aa)
                if(resultPadd && centerBox)
                {
                    if(Math.floor(resultPadd.clientHeight) <= Math.floor(centerBox.clientHeight))
                    {
                        var remNull = centerBox.clientHeight - resultPadd.clientHeight
                        var bb = winBox.clientHeight - headerBox.clientHeight - remNull - 100
                        $('.'+ ele +' .centerBox').css('max-height',bb)
                    }
                }
            }
        }
    },

   /**
     * 文本框只能输入数字
     */
    isNum :function () {//console.log('只能输入数字文本框')
        /**  */
        var $this = this
        $(':input[onlyInputNum=1]').each(function () {
            var _this = $(this)
            console.log('val:'+_this.val())
            if (!$this.isNull(_this.val())) {
                _this.val($this.replaceNuml($(_this).val()))
            }
            _this.css({'ime-mode': 'disabled'})
            _this.keypress(function (event) {
                var key = event.which

                //console.log(_this.val())
                /** 49-57小键盘数字 */
                if (key == 46 || key == 8 || key == 0 || (key >= 48 && key <= 57)) {
                    return true
                } else {
                    return false
                }
            })
            _this.blur(function () {
                var new_value = $this.replaceNuml($(this).val())
                if (new_value.length == 0) {
                    $(this).val('')
                } else {
                    $(this).val(new_value)
                }
            })
        })

        $(':input[onlyInputNum=2]').each(function () {
            var _this = $(this)
            if (!$this.isNull(_this.val())) {
                _this.val(this.replaceNuml($(_this).val()))
            }
            _this.css({'ime-mode': 'disabled'})
            _this.keypress(function (event) {
                var key = event.which
                /** 49-57小键盘数字 */
                if (key == 46 || key == 8 || key == 0 || (key >= 48 && key <= 57)) {
                    return true
                } else {
                    if(/^(\d{13}|\d{16})[\dxX]$/.test( _this.val() )){
                        return true
                    }
                    return false
                }
            })
            _this.blur(function () {
                _this.val( _this.val().replace(/[^\dA-Za-z$]/g, '') )
            })
        })

    },
    /** 替换成纯数字字符串 */
    replaceNuml: function (val) {
        if (this.isNull(val))
            val = ''
        else {
            if (isNaN(val)) {
                val = val.replace(/[^\d\.$]/g, '')
            }
        }
        return val
    },

    /*	磊哥
     *	方法：实现您的位置
     */
    loadHead: function () {
        var actives= $('.actives').html()
        if(this.isNull(actives)){
            actives=''
        }else{
            actives=actives.trim()
        }
        var light= $('.light').text()
        if(this.isNull(light)){
            light=''
        }else{
            light='>'+light.trim()
        }
        var publicListHover= $('.publicListHover').html()
        if(this.isNull(publicListHover)){
            publicListHover=''
        }else {
            publicListHover='>'+publicListHover.trim()
        }
        $('.icon-shouyeshouye').next('span').html('您的位置：'+actives+light+publicListHover)
    },

    /*禹
     *阻止浏览器默认事件
     * */
    stopBOM:function (e){
        if(e && e.stopPropagation) 	e.stopPropagation()
        else 						window.event.cancelBubble = true
        if(e && e.preventDefault) 	e.preventDefault()
        else 						window.event.returnValue = false
    },
    //巧   身份证信息获取出生日期
    Datetype:function(birthCard){
        var birth=birthCard.slice(6,14)
        var birthDay=birth.replace(/(\d{4})(\d{2})(\d{2})/g,'$1-$2-$3')
        return birthDay
    },
    //巧  数据统计标题切换时颜色变化
    addBlue: function(ele){
        $(ele.target).css({'background': '#29335c','color': 'white'})
        $(ele.target).siblings('li').css({'background':'none','color':'#333333'})
    },
    //禹 解决点击冒泡影响列表选择
    stopPa:function(e){
        e.stopPropagation()
    },

    /*禹
     input框中转成人民币货币形式
     */
    toRMB:function(number, places, symbol, thousand, decimal) {
        number = number || 0
        places = !isNaN(places = Math.abs(places)) ? places : 2
        symbol = symbol !== undefined ? symbol : '￥'
        thousand = thousand || ','
        decimal = decimal || '.'
        var negative = number < 0 ? '-' : '',
            i = parseInt(number = Math.abs(+number || 0).toFixed(places), 10) + '',
            j = (j = i.length) > 3 ? j % 3 : 0
        return symbol + negative + (j ? i.substr(0, j) + thousand : '') + i.substr(j).replace(/(\d{3})(?=\d)/g, '$1' + thousand) + (places ? decimal + Math.abs(number - i).toFixed(places).slice(2) : '')
    },

    /*禹
     *录入订单 编辑订单中人民币形式转成number传给后台
     */
    toNum: function(price){
        price += ''
        return price.replace(/[^\d\.$]/g, '')//[^]在里面代表非字符的任意字符
    },
    /*
     *禹
     *智能联想生成下拉选项 
     */
    creSele:function (obj){
        var autocomplete = $(obj.el).autocomplete({
            hints: obj.data,
            width: obj.width,
            height: obj.height,
            val:obj.val,
            inputClass:obj.inputClass,
            placeholder:obj.placeholder,
            onSubmit: function(text){
                obj.backball(text)
            }
        })
        return autocomplete
    },
    /*获取json文件中的城市*/
    getCity:function(){
        var city
        $.ajax({type:'get',url:'../assets/json/cityjson.json',async:false,success:function(data){
            city = data
        }
        })
        return city
    },
    /*获取完json数据后转成id 传给后台*/
    getSearId: function(data){
        var id,city = this.getCity()
        $.each(city,function(idx,item){
            if(item.name == data){
                id = item.id.split(',')
                return
            }
        })
        return id
    },
    /*判断保险单是否有勾选**/
    policyFun:function(obj){
        if(obj){
            for(var item in obj){
                if(obj[item]) return true
            }
        }
    },
    webuploader: function (pick, callback) {
        var uploader = webUploader.create({
            auto: true,
            // swf文件路径
            swf: 'iframe/webUploader/Uploader.swf',

            // 文件接收服务端。
            // server: 'http://120.76.233.85:18082/file_upload/file_upload_img/webUploadAction.do',
            // server: 'http://www.ksglxt.com/file_upload_test/file_upload_img/webUploadAction.do',
            server: config.UPLOAD_API_URL,
            // 选择文件的按钮。可选。
            // 内部根据当前运行是创建，可能是input元素，也可能是flash.
            pick: pick,
            // 不压缩image, 默认如果是jpeg，文件上传前会压缩一把再上传！
            resize: false,
            sendAsBinary: true,
            duplicate :true

        })
        // // 当有文件被添加进队列的时候
        // uploader.on('fileQueued', function (file) {
        //     console.log(file);
        // });
        // $('#uploader').find('.ctlBtn').on('click', function () {
        //     uploader.upload();
        // });

        // // 文件上传过程中创建进度条实时显示。
        // uploader.on('uploadProgress', function (file, percentage) {
        //     var $li = $('#' + file.id),
        //         $percent = $li.find('.progress .progress-bar');
        //     // 避免重复创建
        //     if (!$percent.length) {
        //         $percent = $('<div class='progress progress-striped active'>' +
        //             '<div class='progress-bar' role='progressbar' style='width: 0%'>' +
        //             '</div>' +
        //             '</div>').appendTo($li).find('.progress-bar');
        //     }
        //     $li.find('p.state').text('上传中');
        //     $percent.css('width', percentage * 100 + '%');
        // });
        //上传成功
        uploader.on('uploadSuccess', function (file, data) {
            callback(data)
            // console.log(file)
            //$('#' + file.id).find('p.state').text('已上传');
        })
        //上传失败
        uploader.on('uploadError', function (file) {
            //  $('#' + file.id).find('p.state').text('上传出错');
            console.log(file)
        })

        // uploader.on('uploadComplete', function (file) {
        //     $('#' + file.id).find('.progress').fadeOut();
        // });

    },
	selectUser:function(e){
		var param={};
		param['dId']=e.value;
		this.ajaxPost('manager/selectDepartmentRoleList.do',param,function(data){
			console.log(data);
			console.log('selectUser');
			var html=[];
			html.push('<option value="">选择人员</option>');
			if(data.type>0){
				$.each(data.content, function(i,t) {
					html.push('<option value="'+t.id+'">'+t.realName+'</option>');
				});
			}
			$('#select_sendM').html(html.join(''));
			if(param.dId == '-1'){
				console.log($(e));
				if($(e).parent().prev('.se-re-jq').length>0){
					console.log('lplplp');
					var rr=$(e).parent().prev().find('select').val();
					param.dId=rr;
				}
			}
			$('#select_sendM').attr('data-id',param.dId);
		})
	}
    ,
    timeComparison: function(startDate, endDate) {
        if(startDate && endDate) { //可扩展
            let beginTime = new Date(startDate).getTime()
            let endTime = new Date(endDate).getTime()
            if (beginTime > endTime) {
                return true
            }
        }
        return false
    }
    ,
    loadImage: function(url,target) {
        let img = new Image();
        img.src = url;
        img.onload = function () {
            $('.'+target).removeClass('load').attr('src',img.src)
        }
    }
    ,
    /*imgList: function(id){
        // console.log('imgList',id)
          var options = {
        // inline: true,
            url: 'data-original',
            show: function (){
                viewer.update();
            },
            build: handler,
            built: handler,
            show: handler,
            shown: handler,
            hide: handler,
            hidden: handler
          };
          var handler = function (e) {
            console.log(e, e.type);
          };  
        setTimeout(function(){
            // console.log('timeout:', $('#gallery'+id))
            $('#gallery'+id).viewer(options);
        },200)
    }*/
    imgList: function(id,modal){
        console.log('imgList',id)
        if(modal){
            //模态框 图片预览
            setTimeout(function(){
                var viewer = new Viewer($('.modal-dialog')[0],{
                    url: 'data-original',
                    show: function (){
                        viewer.update();
                        // viewer.full()();
                    }
                });
            },300)
        }
        else{
            setTimeout(function(){
                var viewer = new Viewer(document.getElementById('gallery'+id),{
                    url: 'data-original',
                    show: function (){
                        viewer.update();
                        // viewer.full()();
                    }
                });
            },300)
        }
        
    }

}